package com.open.capacity.task.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.CodeEnum;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.task.dao.CommentDao;
import com.open.capacity.task.model.TaskComment;
import com.open.capacity.task.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    CommentDao commentDao;

    @Override
    /**
     * 根据前台传输条件分页查询相关评论信息
     */
    public PageResult<TaskComment> findComment(Map<String, Object> params) throws ServiceException {
        try {
            //获取起始页和每页显示条数
//            PageHelper.startPage(MapUtils.getInteger(params, PageUtil.PAGE), MapUtils.getInteger(params, PageUtil.LIMIT));
            List<TaskComment> list = commentDao.findComment(params);
//            PageInfo<TaskComment> info = new PageInfo<>(list);
            return PageResult.<TaskComment>builder()
                    .data(list)
                    .code(CodeEnum.SUCCESS.getCode())
                    .count((long) list.size())
                    .build();
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public Result add(TaskComment taskComment) {
        try {
            int result = commentDao.add(taskComment);
            if (result == 1) {
                return Result.succeed("评论成功");
            }
            return Result.failed("评论失败");
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @Override
    public Result delete(String id) {
        try {
            int result = commentDao.delete(id);
            if (result != 0) {
                return Result.succeed("删除成功");
            }
            return Result.failed("删除失败");
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 根据用户id查询用户昵称，展示评论用到
     * @param id
     * @return
     */
    @Override
    public Result findUserById(String id) {
       try{
           String nickName = commentDao.findUserById(id);
           return Result.succeedWith(nickName,CodeEnum.SUCCESS.getCode(),"操作成功");
       }catch (Exception e){
           log.debug(e.getMessage());
           throw new ServiceException(e);
       }
    }

    /**
     * 根据任务id查询出属于该任务的所有的一级评论
     * @param params 参数应该包含任务id和当前页显示多少条评论（page和limit），
     * @return
     */
    @Override
    public PageResult<TaskComment> findCommentById(Map<String, Object> params) {
        try{
            PageHelper.startPage(MapUtils.getInteger(params,PageUtil.PAGE),MapUtils.getInteger(params,PageUtil.LIMIT));
            PageInfo<TaskComment> info  = new PageInfo<>(this.commentDao.findCommentById(params));
            return PageResult.<TaskComment>builder()
                    .data(info.getList())
                    .code(CodeEnum.SUCCESS.getCode())
                    .count(info.getTotal())
                    .build();
        }catch (Exception e){
            log.debug(e.getMessage());
            throw  new ServiceException(e);
        }
    }

    @Override
    public Result findSubCommentById(Integer id) {
        try{
            List<TaskComment> list = commentDao.findSubCommentById(id);
            return Result.succeedWith(list,CodeEnum.SUCCESS.getCode(),"查询成功");
        }catch (Exception e){
            log.debug(e.getMessage());
            throw  new ServiceException(e);
        }
    }

    /**
     * 根据评论的id查询该评论的点赞数
     * @param id
     * @return
     */
    @Override
    public Result getLikeCountByCmtId(Integer id) {
        try{
            int result = commentDao.getLikeCountByCmtId(id);
            return Result.succeedWith(result,CodeEnum.SUCCESS.getCode(),"操作成功");
        }catch (Exception e){
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 根据用户id和评论id，对评论进行点赞或取消点赞。用
     * 户id判断该用户是否已经对该评论点赞过，如果点赞了，则操作取消点赞，
     * 如果没有点过赞，则 进行点赞
     * @param userId
     * @param cId
     * @return
     */
    @Override
    @Transactional
    public Result giveLikeOrCancel(String userId, Integer cId) {
        try{
            if (judgeLike(userId,cId)){
                int result = commentDao.cancel(cId);//取消点赞，评论点赞量-1
                commentDao.delUserCommentRelation(userId,cId);
                return result==1?Result.succeed("取消点赞成功"):Result.failed("取消点赞失败");
            }else {
                int result = commentDao.giveLike(cId);//进行点赞，评论点赞量+1
                commentDao.addUserLikeComment(userId,cId); //对用户评论关联表进行数据新增;
                return result==1?Result.succeed("点赞成功"):Result.failed("点赞失败");
            }
        }catch (Exception e){
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 判断用户是否对该评论点赞过
     * @param userId
     */
    private boolean judgeLike(String userId,Integer cId){
        int result = commentDao.judgeLike(userId,cId);
        if (result==1){
            return true;
        }
        return false;
    }
}
